package tangmukeji.com.rxjava2retrofit2.api;

import android.content.Context;

import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;
import tangmukeji.com.rxjava2retrofit2.base.BaseBean;
import tangmukeji.com.rxjava2retrofit2.base.Subject;

/**
 * Created by Administrator on 2018/3/22 0022.
 * 对网络请求的配置值，以及应用层的网络方法的封装
 */

public class HttpManager {

    private static String baseUrl = ConstantUrl.URL_BASE;
    private static final int DEFAULT_TIMEOUT = 5;
    private Context mContext;
    private Retrofit mRetrofit;
    //
    private ApiService apiService;

    private static class SingleHolder {
        private static HttpManager httpManager = null;

        public static HttpManager getInstance(Context context) {
            if (httpManager == null) {
                httpManager = new HttpManager(context);
            }
            return httpManager;
        }

    }

    public HttpManager(Context mContext) {
        this.mContext = mContext;
        mRetrofit = new Retrofit.Builder()
                .client(initOkHttpClient().build())
                .baseUrl(baseUrl)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        apiService = mRetrofit.create(ApiService.class);
    }

    public static HttpManager init(Context context) {
        return SingleHolder.getInstance(context);
    }


    /**
     * 创建okhttp的构建
     *
     * @return
     */
    private OkHttpClient.Builder initOkHttpClient() {
        //日志显示级别
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS);
        //添加 token 过期拦截,和日志打印
        builder.addInterceptor(new TokenInterceptor());
        return builder;
    }

    /**
     * 请求方法
     *
     * @param strat
     * @param count
     * @param subscriber
     */
    public void getMovie(int strat, int count, BaseBeanObserver<List<Subject>> subscriber) {
        apiService.getMovie(strat, count).compose(RxSchedulers.<BaseBean<List<Subject>>>compose(mContext)).subscribe(subscriber);
    }

}
